<?php
/**
 * Created by PhpStorm.
 * User: meng
 * Date: 2023/9/5
 * Time: 11:45
 */

namespace lib\exception;

use Max\VarDumper\Dumper;
use Max\VarDumper\DumperHandler;
use Throwable;
use Webman\Exception\ExceptionHandler as BaseExceptionHandler;
use Webman\Http\Request;
use Webman\Http\Response;

class ExceptionHandler extends BaseExceptionHandler
{
    use DumperHandler;

    public $dontReport = [
        HttpResponseException::class,
        BaseException::class,
        Dumper::class
    ];

    public function render (Request $request, Throwable $exception): Response {
        if ($exception instanceof HttpResponseException) { // 自定义响应输出
            return $exception->getResponse();
        } else if ($exception instanceof BaseException) { // 自定义异常
            $code = $exception->code;
            $message = $exception->message;
            $errCode = $exception->errCode;
            $json = [
                'code'    => $errCode,
                'message' => $message,
                'data'    => $exception->data,
            ];
            return new Response($code, ['Content-Type' => 'application/json'], json_encode($json, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
        } else if ($exception instanceof Dumper) { // 网页打印功能
            return \response(self::convertToHtml($exception));
        } else { // 其他异常
            $code = $exception->getCode();
            if ($request->expectsJson()) {
                $json = ['code' => $code ? : 500, 'message' => $this->debug ? $exception->getMessage() : 'Server internal error'];
                $this->debug && $json['traces'] = (string)$exception;
                return new Response(200, ['Content-Type' => 'application/json'],
                    json_encode($json, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
            }
            $error = $this->debug ? nl2br((string)$exception) : 'Server internal error';
            return new Response(500, [], $error);
        }
    }
}
